<template>
<div>

<el-row>
	<el-form :inline="true"  class="demo-form-inline">
		<el-form-item label="">
			<el-amap-search-box class="search-box" 
			:search-option="searchOption" 
			:on-search-result="onSearchResult"></el-amap-search-box>
		</el-form-item>
		
		<el-form-item label="坐标" >
			[{{ lng }}, {{ lat }}]
		</el-form-item>

		<el-form-item label="地址：">
			{{ address }}
		</el-form-item>

		<el-form-item >
			<el-button type="primary" class="mt5" @click="onSubmit">保存</el-button>
		</el-form-item>
	</el-form>
</el-row>



<div :style="{width: offsetwidth + 'px', height : offsetheight + 'px'}">
<el-amap vid="amapDemo"  
:center="center" 
:amap-manager="amapManager"  
:zoom="zoom" 
:events="events"
class="amap-demo">
	<el-amap-marker vid="component-marker1" :position="[lng, lat]"  ></el-amap-marker>
</el-amap>
</div>
</div>
</template>

<script>
import { mapGetters } from 'vuex'
import VueAMap from 'vue-amap'

let amapManager = new VueAMap.AMapManager();


export default {
	
	name : 'position',
	
	data () {
		let self = this;

		return {
		  	amapManager,
		  	center : [],
		  	zoom : 15,

		  	offsetwidth:document.documentElement.clientWidth - 40,

		  	offsetheight : document.documentElement.clientHeight - 200,

		  	lng : 0,
          	lat : 0,
          	address : '',

          	events: {
				click(e) {
					let { lng, lat } = e.lnglat;
					self.lng = lng;
					self.lat = lat;

					// 这里通过高德 SDK 完成。
					var geocoder = new AMap.Geocoder({
						radius: 1000,
						extensions: "all"
					});        
					geocoder.getAddress([lng ,lat], function(status, result) {
						if (status === 'complete' && result.info === 'OK') {
							if (result && result.regeocode) {
								self.address = result.regeocode.formattedAddress;
								self.$nextTick();
							}
						}
					});        
				}
			},

			searchOption: {
	            city: '沈阳市',
	            citylimit: true
	        },

		}
	},

	props : {

	},

	components : {
		
	},

	computed : {
		...mapGetters({
		  	c : 'center',
		  	city : 'city',
		})
	},

	methods : {
		onSearchResult(pois) {
          let latSum = 0;
          let lngSum = 0;
          console.log(pois);
          if (pois.length > 0) {
            pois.forEach(poi => {
              let {lng, lat} = poi;
              lngSum += lng;
              latSum += lat;
              //this.markers.push([poi.lng, poi.lat]);
            });
            let center = {
              lng: lngSum / pois.length,
              lat: latSum / pois.length
            };

            console.log(center);
            this.center = [center.lng, center.lat];
          }
        },


        onSubmit () {
        	this.$emit('save', {
        		lng : this.lng,
        		lat : this.lat,
        	});
        },
	},

	watch : {
	    
	},

	mounted () {
		this.center = this.c;
		this.searchOption.city = this.city;
	},

}
</script>

<style scoped>

</style>
